package com.atguigu.sort;

import java.util.Arrays;

/**
 * description:
 * Created by 才睡醒 on 2021-06-24
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {-9, 78, 0, 23, -567, 70};
        quickSort(arr,0,arr.length-1);
        System.out.println(Arrays.toString(arr));
    }

    public static void quickSort(int[] arr, int left, int right) {
        int l = left;
        int r = right;
        int mid = arr[(l + r) / 2];
        int temp = 0;
        while (l < r) {
            while (arr[l] < mid) {
                l += 1;
            }
            while (arr[r] > mid) {
                r -= 1;
            }
            if (l >= r) {
                break;
            }
            temp = arr[r];
            arr[r] = arr[l];
            arr[l] = temp;
            //如果交换完后，发现这个arr【l】== mid，往前再走一步，r--
            if (arr[l] == mid) {
                r -= 1;
            }
            //同理
            if (arr[r] == mid) {
                l += 1;
            }
        }
        //如果l == r,必须l++ ， r-- ,否则会出现栈溢出
        if(l == r) {
            l += 1;
            r -= 1;
        }
        //向左递归
        if(left<r){
            quickSort(arr,left,r);
        }
        //向右递归
        if(right>l){
            quickSort(arr,l,right);
        }
    }
}
